<template>
  <el-pagination
    class="pagination_block"
    :current-page="page"
    :page-size="size"
    :page-sizes="pageSizes"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    :pager-count="pagerCount"
    
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <!-- small default-->
</template>

<script setup>
import { debounce } from "@/utils";

const props = defineProps({
  total: {
    required: true,
    type: Number,
  },
  page: {
    type: Number,
    default: 1,
  },
  size: {
    type: Number,
    default: 10,
  },
  pagerCount: {
    type: Number,
    default: 5,
  },
});
 const pageSizes = ref();
const emits = defineEmits(["change"]);

// 防抖处理函数
const calcPageCallback = ref(null);

// 初始化防抖函数
calcPageCallback.value = debounce(300, () => {
  calcPage();
});

// 监听关键属性变化
watch(
  () => [props.total, props.page, props.size],
  () => {
    calcPageCallback.value();
  }
);
onMounted(() => {
  // 计算页码列表
  if (!props.size) {
    pageSizes.value = [10, 20, 40, 80, 100];
  } else {
    const base = props.size;
    pageSizes.value = [base, base * 2, base * 4, base * 8, base * 10];
  }
});
// 计算有效页码
const calcPage = () => {
  const { total, size, page } = props;
  if (size) {
    const lastPage = Math.ceil(total / size) || 1;
    if (lastPage < page) {
      handleCurrentChange(lastPage)
    }
  }
};

// 页码变更处理
const handleCurrentChange = (newPage) => {
  emits("change", {
    page: newPage,
    size: props.size,
  });
};

// 每页条数变更处理
const handleSizeChange = (newSize) => {
  emits("change", {
    page: props.page,
    size: newSize,
  });
};
</script>
<style lang="scss" scoped>
.pagination_block{
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>